import Vue from "vue";
import axios from "axios";
import qs from "qs";
import { Toast } from "vant";

const host = "https://doumi888.com";

Vue.prototype.$host = host;

if (process.env.NODE_ENV == "development") axios.defaults.baseURL = host;

// 创建axios 实例
const http = axios.create({
  baseURL: host,
  timeout: 20000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
  }
});

// request 拦截器
http.interceptors.request.use(
  config => {
    // 自定义加载图标
    // Toast.loading({
    //   message: "加载中...",
    //   forbidClick: true
    // });
    // console.log(config);
    let p = { token: "29a11b265515fca3d0a57d7e487c081a", uid: "27589" };
    let u = window.sessionStorage.getItem("u");
    if (u) {
      u = JSON.parse(u);
      p.uid = u.id;
      p.token = u.token;
    }
    // alert("当前用户编号" + p.uid);
    if (config.params) {
      config.params = {
        ...config.params,
        ...p
      };
    }
    if (config.data) {
      config.data = {
        ...config.data,
        ...p
      };
    }

    config.data = qs.stringify(config.data, {
      allowDots: true
      // indices: false
      // arrayFormat: "indices"
    });
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response 拦截器
http.interceptors.response.use(
  response => {
    const res = response.data;
    // if (res.code != 0) Message.error(res.message);
    // Toast.clear();
    return res;
  },
  error => {
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "错误请求";
          break;
        case 401:
          error.message = "未授权，请重新登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求错误,未找到该资源";
          break;
        case 405:
          error.message = "请求方法未允许";
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器端出错";
          break;
        case 501:
          error.message = "网络未实现";
          break;
        case 502:
          error.message = "网络错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网络超时";
          break;
        case 505:
          error.message = "http版本不支持该请求";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      error.message = "连接到服务器失败";
    }
    // Toast.clear();
    Toast("网络不畅通~");
    return Promise.reject(error);
  }
);

/**
 * get请求
 * @param {*} u 路径
 * @param {*} p 参数
 */
const get = function(u, p) {
  return http.get(u, { params: p });
};

/**
 * post请求
 * @param {*} u 路径
 * @param {*} p 参数
 */
const post = function(u, p) {
  return http.post(u, p);
};

Vue.prototype.$post = post;
Vue.prototype.$get = get;
Vue.prototype.$http = http;
Vue.prototype.$axios = axios;
export { get, post, http };
